package com.loveazure.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Vector;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.loveazure.eo.Cent;
import com.loveazure.eo.Dict;

public class WebDict {
	private static SAXReader reader = new SAXReader();
	private final static String URLTemp = "http://dict.cn/ws.php?q=";

	public static Dict getDict(String word) {
		try {
			Document doc = reader.read(new URL(URLTemp + word).openStream());
			System.out.println(word.charAt(0));
			Element root = doc.getRootElement();

			Dict dic = new Dict();
			Vector<Cent> v = new Vector<Cent>();

			for (Object o : root.elements()) {
				Element e = (Element) o;
				if (e.getName().equals("key")) {
					dic.setName(e.getTextTrim());
				} else if (e.getName().equals("audio")) {
					dic.setAudio(e.getTextTrim());
				} else if (e.getName().equals("pron")) {
					dic.setPron(e.getTextTrim());
				} else if (e.getName().equals("def")) {
					dic.setDef(e.getTextTrim());
				} else if (e.getName().equals("sent")) {
					Cent cent = new Cent();
					for (Object subo : e.elements()) {
						Element sube = (Element) subo;
						if (sube.getName().equals("orig")) {
							cent.setOrig(sube.getTextTrim());
						} else if (sube.getName().equals("trans")) {
							cent.setTrans(sube.getTextTrim());
						}
					}
					v.add(cent);
				}
			}

			if (dic.getName() == null || "".equals(dic.getName())) {
				return null;
			}

			dic.setCent(new HashSet<Cent>());

			for (Cent c : v) {
				c.setDict(dic);
				dic.getCent().add(c);
			}

			return dic;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean checkWord(String word) {
		
		try {
			InputStream is = new URL(URLTemp + URLEncoder.encode(word))
					.openStream();
			InputStreamReader isr = new InputStreamReader(is, "GBK");
			BufferedReader br = new BufferedReader(isr);
			Document doc = reader.read(isr);
			Element root = doc.getRootElement();
			for (Object o : root.elements()) {
				Element e = (Element) o;
				if (e.getName().equals("def")
						&& e.getTextTrim().equals("Not Found")) {
					return false;

				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
			return false;
		}

	}

	public static void main(String[] args) {
		System.out.println(checkWord("stand"));
	}
}
